<template>
  <n-modal
    v-model:show="showModal"
    :show-icon="false"
    preset="dialog"
    :title="title"
    :style="{ width: props.width + 'px' }"
    @update:show="handleUpdateShow"
  >
    <n-form :model="formData" :rules="rules" ref="formRef" label-width="auto" label-placement="top">
      <n-grid :cols="1" :x-gap="24">
        <n-form-item-gi label="类目名称" path="fileCgyNm">
          <n-input placeholder="请输入文件类目名称" v-model:value="formData.fileCgyNm" />
        </n-form-item-gi>
        <n-form-item-gi v-if="formData.fileCgyPid === 'ROOT' && !bizId" label="文件桶" path="bcktId">
          <n-select v-model:value="formData.bcktId" :options="bcktList" value-field="bcktId" label-field="bcktNm" />
        </n-form-item-gi>
      </n-grid>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="() => handleUpdateShow(false)">取消</n-button>
        <n-button type="primary" :loading="saveBtnLoading" @click="handleSave">
          <template #icon>
            <n-icon>
              <SaveOutlined />
            </n-icon>
          </template>
          保存
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { reactive, ref, unref, watch } from 'vue';
import type { FormRules, FormInst } from 'naive-ui';
import { SaveOutlined } from '@vicons/antd';
import { fileBcktQry } from '@yanfan/bmpfl-tsapi/file-bckt';
import type { FileBcktQryOutput_FileBcktDto } from '@yanfan/bmpfl-tsapi/file-bckt/types.d';
import { fileCgyGet, fileCgySav } from '@yanfan/bmpfl-tsapi/file-cgy';
import type { FileCgyQry001Output_FileCgyDto } from '@yanfan/bmpfl-tsapi/file-cgy/types.d';
import type { OptionalKeys } from '@yanfan/admin-layout/types';
import { removeFormEmptyField } from '@yanfan/admin-layout/utils';

defineOptions({
  name: 'BmpflFileCgyEdit',
});

type IFileCgyTreeOption = OptionalKeys<FileCgyQry001Output_FileCgyDto, 'children'>;

class FormData {
  fileCgyId = '';
  fileCgyNm = '';
  fileCgyPid = '';
  fileTpCd: null | string = null;
  bcktId: null | string = null;
  rmrk = '';
}

const props = withDefaults(
  defineProps<{
    show: boolean;
    width?: number;
    bizId?: string;
    parentCgy: IFileCgyTreeOption | null;
    fileTpCd: string;
  }>(),
  {
    show: false,
    width: 530,
    parentCgy: null,
  },
);

const emits = defineEmits<{
  (e: 'update:show', show: boolean): void;
  (e: 'refresh'): void;
}>();

const rules: FormRules = {
  fileCgyNm: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入文件类目名称',
  },
  bcktId: {
    required: true,
    trigger: ['change'],
    message: '请选择文件桶',
  },
};

const title = ref<string>('新建');
const formRef = ref<FormInst | null>(null);
const showModal = ref<boolean>(false);
const saveBtnLoading = ref<boolean>(false);
const formData = reactive(new FormData());
const bcktList = ref<FileBcktQryOutput_FileBcktDto[]>([]);

watch(
  () => unref(props).show,
  (show) => {
    showModal.value = show;
    if (showModal.value) {
      loadFileBcktData();
      if (props.bizId) {
        title.value = '编辑';
        fileCgyGet({ fileCgyId: props.bizId }).then((data) => {
          Object.assign(formData, data);
        });
      } else {
        title.value = '新建';
        Object.assign(formData, new FormData(), {
          fileTpCd: props.fileTpCd,
          fileCgyPid: props.parentCgy?.fileCgyId ? props.parentCgy.fileCgyId : 'ROOT',
          bcktId: props.parentCgy?.fileCgyId ? props.parentCgy.bcktId : null,
        });
      }
    }
  },
);

function handleUpdateShow(value: boolean) {
  emits('update:show', value);
}

function handleSave() {
  formRef.value?.validate((errors) => {
    if (!errors) {
      saveBtnLoading.value = true;
      fileCgySav(removeFormEmptyField(formData))
        .then(() => {
          handleUpdateShow(false);
          window.$message.success('保存成功');
          emits('refresh');
        })
        .finally(() => (saveBtnLoading.value = false));
    } else {
      window.$message.error('请填写完整信息');
    }
  });
}

function loadFileBcktData() {
  fileBcktQry({ pageIndx: 1, pageSize: 5000 }).then((data) => {
    bcktList.value = data.list;
  });
}
</script>

<style lang="scss" scoped></style>
